package com.example.mycardgame

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.appcompat.app.AppCompatActivity
import androidx.gridlayout.widget.GridLayout
import android.widget.Button
import android.widget.ImageButton
import com.example.mycardgame.model.Card
import com.example.mycardgame.model.CardGameModel
import com.example.mycardgame.R

class CardGameActivity : AppCompatActivity() {
    private lateinit var gameModel: CardGameModel
    private lateinit var gridLayout: GridLayout
    private lateinit var restartBtn: Button
    private val handler = Handler(Looper.getMainLooper())

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_card_game)

        gameModel = CardGameModel()
        gridLayout = findViewById(R.id.card_grid)
        restartBtn = findViewById(R.id.btn_restart)

        initGame()
        restartBtn.setOnClickListener { initGame() }
    }

    private fun initGame() {
        gameModel.initGame()
        setupCardGrid()
    }

    private fun setupCardGrid() {
        gridLayout.removeAllViews()
        gridLayout.columnCount = 4
        gameModel.cards.forEach { card ->
            ImageButton(this).apply {
                setImageResource(R.drawable.card_back)
                layoutParams = GridLayout.LayoutParams().apply {
                    width = 150
                    height = 200
                    setMargins(8, 8, 8, 8)
                }
                setOnClickListener { onCardClicked(card, this) }
                gridLayout.addView(this)
            }
        }
    }

    private fun onCardClicked(card: Card, cardBtn: ImageButton) {
        if (card.isMatched || card.isFaceUp) return

        val isMatched = gameModel.onCardClick(card)
        updateCardView(card, cardBtn)

        if (!isMatched && gameModel.shouldFlipBack()) {
            handler.postDelayed({
                gameModel.flipBackUnmatchedCards()
                refreshAllCardViews()
            }, 1000)
        }
    }

    private fun updateCardView(card: Card, cardBtn: ImageButton) {
        cardBtn.setImageResource(if (card.isFaceUp) card.imageResId else R.drawable.card_back)
    }

    private fun refreshAllCardViews() {
        gameModel.cards.forEachIndexed { i, card ->
            (gridLayout.getChildAt(i) as ImageButton).setImageResource(
                if (card.isFaceUp) card.imageResId else R.drawable.card_back
            )
        }
    }
}